package hu.dobrosi.util.io.gps;

import hu.dobrosi.util.StringUtil;

import java.util.Calendar;
import java.util.Date;

import javax.microedition.location.Coordinates;
import javax.microedition.location.Criteria;
import javax.microedition.location.Location;
import javax.microedition.location.LocationException;
import javax.microedition.location.LocationProvider;

public class LocationHandler {
	private double[] location;
	private LocationProvider lp;
	private Calendar calendar;
	private float velocity;
	private boolean hasSignal;

	public LocationHandler() {
		Criteria cr = new Criteria();
		cr.setHorizontalAccuracy(500);
		try {
			lp = LocationProvider.getInstance(cr);
		} catch (LocationException e) {
			StringUtil.logger.clear();
			StringUtil.logger.print(e);
		}
	}

	public void read(int lineNumber) {
		try {
			Location l = lp.getLocation(lineNumber);
			if (l != null) {
				calendar = Calendar.getInstance();
				calendar.setTime(new Date(l.getTimestamp()));
				velocity = l.getSpeed();
				Coordinates c = l.getQualifiedCoordinates();
				if (c != null) {
					location = new double[] { c.getLatitude(),
							c.getLongitude(), c.getAltitude() };
					hasSignal = true;
				} else {
					hasSignal = false;
				}
			}
		} catch (LocationException e) {
			StringUtil.logger.clear();
			StringUtil.logger.print(e);
		} catch (InterruptedException e) {
			StringUtil.logger.clear();
			StringUtil.logger.print(e);
		}
	}

	public Calendar getCalendar() {
		return calendar;
	}

	public void setCalendar(Calendar calendar) {
		this.calendar = calendar;
	}

	public float getVelocity() {
		return velocity;
	}

	public void setVelocity(float velocity) {
		this.velocity = velocity;
	}

	public boolean isHasSignal() {
		return hasSignal;
	}

	public void setHasSignal(boolean hasSignal) {
		this.hasSignal = hasSignal;
	}

	public double[] getLocation() {
		return location;
	}

	public void setLocation(double[] location) {
		this.location = location;
	}
}
